#! /usr/bin/python
# -*- coding: cp1250 -*-

import re
import string
import sys
import glob
import os
import time
import pepe.p_txt.bigtxt as bt
import pepe.p_datetime.stopwatches as pds

iso_time_now = lambda : time.strftime ("%Y-%m-%dT%H:%M:%S", time.localtime())
fw_slash = lambda x: re.sub(r'\\', '/', x)

class Info:
    """ Get info about text file (passed and reused as dictionary):

        @FILE           : full path input file name
        @COLUMNS        : columns count
        @ROWS           : rows count
        @CSPAN          : columns header names and spans
        @RUN_DURATION   : time needed to process data
        @RUN_TIMESTAMP  : script run timestamp 
    """
    def __init__(self, file, cdelimiter='', skipRows=0):
        ''' setup of initial values 
        '''
        self.file = "%s/%s"%(fw_slash(os.getcwd()), file)
        self.header = ''
        self.cdelimiter = cdelimiter
        self.skiprows = int(skipRows)
        self.customheader = ''
        self.rowtoskip = 0
        self.info = {    '@FILE':"%s/%s"%(fw_slash(os.getcwd()), file)
                        ,'@COLUMNS':[]
                        ,'@CSPAN':{}
                        ,'@CDELR': cdelimiter
                    }

    def setHeader(self, header):
        ''' setup custom header 
        '''
        self.header = header
        self.info.update({'@HEADER':string.split(header, self.cdelimiter)})
        cols = self.columns(self.header)
        self.ifHeader(cols)

    def getHeader(self, headerFile=''):
        ''' get header columns
        '''
        if headerFile == '':
            of = open(self.file, 'r')
        else:
            of = open(headerFile, 'r')
        header = re.sub('\n', '', of.readline())
        cols = string.split(header, self.cdelimiter)
        self.info.update({'@HEADER':cols})
        of.close()

    def getRow(self, rowNo):
        ''' get row with specific no
        '''
        cnt = 0
        of = open(self.file, 'r')
        while cnt < rowNo:
            line = re.sub('\n', '', of.readline())
            cols = string.split(line, self.cdelimiter)
            cnt += 1
        of.close()
        return cols

    def columns(self, line):
        ''' count columns
        ''' 
        cols = string.split(line, self.cdelimiter)
        if len(cols) not in self.info['@COLUMNS']:
            self.info['@COLUMNS'].append(len(cols))
        return cols

    def ifHeader(self, columns):
        for i, v in enumerate(columns):
            i = 'c' + string.zfill(str(i), 3)
            header = re.sub('\W', '', v)
            if header == '': header = '_'
            self.info['@CSPAN'][i] = {'HEADER':header, 'SPAN':0}

    def cxHeader(self, columns):
        res = []
        for i, v in enumerate(columns):
            i = 'c' + string.zfill(str(i), 3)
            self.info['@CSPAN'][i] = {'HEADER':i, 'SPAN':0}
            res.append(i)
        self.header = string.join(res, self.cdelimiter)

    def ifData(self, columns):
        #print columns
        for i, v in enumerate(columns):
            i = 'c' + string.zfill(str(i), 3)
            span = {'SPAN':len(string.strip(v))}
            
            #print len(string.strip(v))
            #print self.info['@CSPAN'][i]['SPAN']
            if len(string.strip(v)) > self.info['@CSPAN'][i]['SPAN']:
                self.info['@CSPAN'][i].update(span)

    def getInfo(self):
        # stop-watches
        sw = pds.SW()
        sw.start()

        all_cnt = 0
        dat_cnt = 0
        for line in bt.lines(self.file):
            line = re.sub('\n', '', line)

            if all_cnt <= self.skiprows:
                pass
            else:
                if self.header == '':
                    self.cxHeader(self.columns(line))
                self.ifData(self.columns(line))
                dat_cnt += 1
            all_cnt += 1
        sw.stop()
        self.info.update({'@ROWS':dat_cnt})
        self.info.update({'@RUN_DURATION':sw.pp()})
        self.info.update({'@RUN_TIMESTAMP':iso_time_now()})
        return self.info

def pp(i):
    """ Pretty print INFO dictionary
    """
    print '-'*35
    for k in sorted(i.keys()):
        if k in ('@CSPAN'):
            cs = i[k]
        else:
            print k, i[k]
    print '@CSPAN'
    for c in sorted(cs.keys()):
        print '\t', c, cs[c]
    print """
    import pepe.p_utils.txti as ti
    i = ti.Info(file='new.txt', cdelimiter='^', skipRows=0)
    ti.pp(i.getInfo())
    """

def ui():
    """ User interface : if runned per command line
    """
    # input file name
    if len(sys.argv) == 1:  f = str(raw_input("Enter a file name: "))
    else:                   f = sys.argv[1]
    # column delimiter
    d = str(raw_input("Enter a column delimiter (default '^'): "))
    # skip how many rows
    s = str(raw_input("Skip how many rows (default 0): "))

    if d in (''): d = '^'
    #if hh in ('True', 'true', 'y', 'Y', ''): hh = True
    if s in (''): s = 0

    i = Info(f, d, s)
    di = i.getInfo()
    return di

if __name__ == '__main__':
    """ """
    #testdata/testdata.dat
    di = ui()
    pp(di)
    print di

    #i = Info('testdata/testdata.dat', '^', 1)
    #pp(i.getInfo())

